﻿using System;
using UnityEngine;


//管理所有定时器
public class TimerMgr : Singleton<TimerMgr>
{
    public event Action<float> TimerLoopCallback;

    /// repeatTimers 小于0表示无限循环
    public Timer CreateTimer(float deltaTime, int repeatTimers, Action callback)
    {
        var timer = new Timer();

        timer.DeltaTime = deltaTime;
        timer.RepeatTimes = repeatTimers;
        timer.Callback = callback;

        //_timerLoopCallback += timer.Loop;
        //_timerLoopCallback -= timer.Loop;
        return timer;
    }
    public Timer CreateTimerAndStart(float deltaTime, int repeatTimers, Action callback)
    {
        var timer = CreateTimer(deltaTime, repeatTimers, callback);
        timer.Start();
        return timer;
    }


    // deltaTime 计时器驱动间隔
    public void Loop(float deltaTime)
    {
        if (TimerLoopCallback != null)
        {
            TimerLoopCallback(deltaTime);
        }
    }


}

//定时器
public class Timer
{
    public Action Callback;
    public int RepeatTimes;
    public float DeltaTime;

    private float _duringTime;//计时的持续时间
    private int _repeatTimers;


    public bool IsRunning = false;

    private void reset()
    {
        _duringTime = 0;
        _repeatTimers = 0;

        Pause();
    }


    public void Start()
    {
        reset();
        IsRunning = true;
        TimerMgr.instance.TimerLoopCallback += Loop;
    }

    public void Pause()
    {
        IsRunning = false;
        TimerMgr.instance.TimerLoopCallback -= Loop;

    }


    public void Stop()
    {
        Pause();
        reset();
    }
    public void Loop(float deltaTime)
    {
        _duringTime += deltaTime;
        //判断间隔时间
        if (_duringTime > DeltaTime || Util.FloatEqual(_duringTime, DeltaTime))
        {
            ++_repeatTimers;
            _duringTime -= DeltaTime;
            if (Callback != null)
            {
                Callback();
            }

            if (RepeatTimes > 0 && _repeatTimers >= RepeatTimes)
            {
                Stop();
            }
        }
        //

    }
}



